// ignore_for_file: invalid_use_of_protected_member

import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';

class UiPageEntrance extends StatefulWidget {
  final Widget? child;
  final Widget? placeholder;
  final UiPageEntranceController? controller;
  final bool lazyLoad;
  final bool enableControlFinishLoad;
  final Function()? onReady;
  final Function()? onAnimationComplated;
  const UiPageEntrance({
    super.key,
    required this.child,
    this.controller,
    this.placeholder,
    this.lazyLoad = true,
    this.onReady,
    this.onAnimationComplated,
    this.enableControlFinishLoad = false,
  });

  @override
  State<UiPageEntrance> createState() => UiPageEntranceState();
}

class UiPageEntranceState extends State<UiPageEntrance> {
  /// 页面动画是否完成
  bool isAnimationCompleted = false;

  /// 网络链接失败
  bool isNetworkError = false;

  /// 当前页面需要登录
  bool isLoginError = false;

  /// 页面加载完成
  bool isComplated = false;

  bool loading = false;

  /// 是否显示加载视图
  bool get isShowPlaceholderView {
    if (widget.enableControlFinishLoad) {
      return !isComplated;
    } else {
      return !isAnimationCompleted;
    }
  }

  /// 是否显示内容视图
  bool get isShowContentView {
    return isAnimationCompleted &&
        !isNetworkError &&
        !isShowPlaceholderView &&
        !isLoginError;
  }

  @override
  void initState() {
    super.initState();
    widget.onReady?.call();
    widget.controller?.bind(this);
  }

  /// 页面过渡动画完成后触发
  pageCompleted(context, [Function()? callback]) {
    if (isAnimationCompleted) {
      return;
    }
    var route = ModalRoute.of(context);
    if (!widget.lazyLoad) {
      callback?.call();
    }
    if (route != null) {
      route.animation?.addStatusListener((status) async {
        if (status == AnimationStatus.completed) {
          if (widget.lazyLoad) callback?.call();
          widget.onAnimationComplated?.call();
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    pageCompleted(context, () {
      setState(() {
        log('pageCompleted');
        isAnimationCompleted = true;
      });
    });

    return Stack(
      children: [
        if (isShowContentView) contentView(),
        if (isShowPlaceholderView) placeholderView(),
        if (isNetworkError) networkErrorView(),
        if (isLoginError) showLoginView(),
        if (loading)
          Positioned.fill(
            child: Container(
              color: Colors.transparent,
              child: Center(
                child: Image.asset(
                  'res/images/loading.gif',
                  width: 70,
                ),
              ),
            ),
          ),
      ],
    );
  }

  /// 主视图
  Widget contentView() {
    return Positioned.fill(
      child: widget.child ?? Container(),
    );
  }

  /// 登录提示视图
  Widget showLoginView() {
    return Positioned.fill(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          var res = await AuthService.instance.isLoginOrToLogin();
          if (res) {
            setState(() {
              isComplated = false;
              isLoginError = false;
            });
            widget.onReady?.call();
          }
        },
        child: SizedBox(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  'res/images/ikons/login.png',
                  width: 200,
                ),
                const Text('请先登录', textScaler: TextScaler.linear(1.2)),
                const SizedBox(height: 5),
                const Text('轻触屏幕登录', textScaler: TextScaler.linear(0.9)),
                const SizedBox(height: 100),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 网络链接失败视图
  Widget networkErrorView() {
    return Positioned.fill(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          setState(() {
            isComplated = false;
            isNetworkError = false;
          });
          widget.onReady?.call();
        },
        child: SizedBox(
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  'res/images/network_fail.png',
                  width: 200,
                ),
                const Text(
                  '网络连接失败！',
                  textScaler: TextScaler.linear(1.2),
                ),
                const SizedBox(height: 5),
                const Text(
                  '请检查网络后轻触屏幕重新尝试',
                  textScaler: TextScaler.linear(0.9),
                ),
                const SizedBox(height: 100),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 加载占位符
  Widget placeholderView() {
    return Positioned.fill(
      child: Container(
        child: widget.placeholder ??
            Center(
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Image.asset(
                  'res/images/loading.gif',
                  width: 70,
                ),
              ),
            ),
      ),
    );
  }
}

class UiPageEntranceController {
  late UiPageEntranceState state;
  bool isInit = false;
  bind(UiPageEntranceState pageState) {
    isInit = true;
    state = pageState;
  }

  bool get isComplated {
    return isInit ? state.isShowContentView : false;
  }

  reload() {
    state.widget.onReady?.call();
  }

  showLoading() {
    state.setState(() {
      state.loading = true;
    });
  }

  hideLoading() {
    state.setState(() {
      state.loading = false;
    });
  }

  complete() {
    state.setState(() {
      state.isAnimationCompleted = true;
      state.isComplated = true;
    });
  }

  setStatus(code) {
    switch (code) {
      case 500:
        state.setState(() {
          state.isComplated = true;
          state.isNetworkError = true;
          state.loading = false;
        });
        break;
      case 10001:
        state.setState(() {
          state.isComplated = true;
          state.isLoginError = true;
          state.loading = false;
        });
        break;
      default:
        state.setState(() {
          state.isComplated = true;
          state.loading = false;
        });
    }
  }
}
